package com.redsoft.spirit.util;
 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;

import com.redsoft.spirit.util.Base64;
//import org.apache.commons.codec.binary.Base64; 
 
/**
 * 封装通常使用到的一些功能.
 * 
 * @author payne
 *
 */
public final class CommonUtil{
    
    /**
     * 私有的构造方法.
     *
     */
    private CommonUtil(){}
    
    /**
     * 将字符串从Unicode转换为GBK的编码方式 .
     * @param as_In 字符串
     * @return 新的编码方式的字符串
     */
	public static String unicodeToGB(String as_In){
		byte[] larrb_Bytes;
		String ls_Out = null;

		if(as_In == null || (as_In.trim()).equals(""))
		return as_In;
		try {
            larrb_Bytes = as_In.getBytes("GBK");
			ls_Out = new String(larrb_Bytes,"ISO8859_1");
		} catch (UnsupportedEncodingException e) { 
            System.out.println(CommonUtil.class.getName() + ".unicodeToGB():" + e.getMessage());
        }
		return ls_Out;
	}

    /**
     * 将字符串从GB（GB2312/GBK等）编码转换为Unicode的编码方式.
     * @param as_In 输入的字符串（GB编码）
     * @return Unicode编码的字符串
     */
	public static String gbToUnicode(String as_In){
        String ls_Out = null;
        if(as_In == null || (as_In.trim()).equals("")) return as_In;
        
        try {
            byte[] larrb_Bytes = as_In.getBytes("ISO8859_1");
            ls_Out = new String(larrb_Bytes,"GBK");
        } catch (Exception e) {
            System.out.println(CommonUtil.class.getName() + ".gbToUnicode():" + e.getMessage());
        }
        return ls_Out;
	}

	public static boolean isNumber(String as_Str) { 
		String ls_String = "";
		char[] larrs_String; 

		if (as_Str == null) return false;

		//get rid of the "," in the string
		larrs_String = as_Str.toCharArray();
		for (int i = 0; i < larrs_String.length; i++) { 
            if (larrs_String[i] != ','){ 
                ls_String += larrs_String[i];
		    }
		}

		try { 
            Double.parseDouble(ls_String);
		} catch (NumberFormatException e) { 
		   return false;
		}

		return true;
	}
	
    /**
     * 格式化数字.
     * @param adbl_Number 数字
     * @param as_Pattern 指定的格式
     * @return 格式化之后的字符串
     */
    public static String format(double adbl_Number,String as_Pattern){
        return formatNumber(adbl_Number,as_Pattern);
    }
    
//    /**
//     * 格式化数字.
//     * @param adbl_Number 数字
//     * @param as_Pattern 指定的格式
//     * @return 格式化之后的字符串
//     */
//	public static String formatNumber(double adbl_Number,String as_Pattern){ 
//		String ls_Formatted;
//
//		try {
//            DecimalFormat  ldecimalformat_Format = new DecimalFormat(as_Pattern);
//			ls_Formatted = ldecimalformat_Format.format(adbl_Number);
//		} catch (Exception e){
//		  	printMsg("formatNumber(): " + e.getMessage());
//		  	ls_Formatted = Double.toString(adbl_Number);
//		}
//
//		return ls_Formatted;
//	}
	
	/**
     * 格式化数字.
     * @param dblNumber 数字
     * @param pattern 指定的格式
     * @return 格式化之后的字符串
     */
    public static String formatNumber(double dblNumber,String pattern) { 
        String formatStr = null;
        try {
            DecimalFormat decFormat = new DecimalFormat(pattern); 
            formatStr = decFormat.format(new BigDecimal(Double.toString(dblNumber))
                    .setScale(decFormat.getMaximumFractionDigits(), BigDecimal.ROUND_HALF_UP));
        } catch (Exception e){
            printMsg("formatNumber(): " + e.getMessage());
            formatStr = Double.toString(dblNumber);
        }
        return formatStr;
    }


    /**
     * 格式化数字.
     * @param ai_Number 数字
     * @param as_Pattern 指定的格式
     * @return 格式化之后的字符串
     */
    public static String format(int ai_Number,String as_Pattern){
        return formatNumber(ai_Number,as_Pattern);
    }
     
    /**
     * 格式化数字.
     * @param ai_Number 数字
     * @param as_Pattern 指定的格式
     * @return 格式化之后的字符串
     */
	public static String formatNumber(int ai_Number,String as_Pattern){
		DecimalFormat ldecimalformat_Format;
		String ls_Formatted;

		try {
			ldecimalformat_Format = new DecimalFormat(as_Pattern);
			ls_Formatted = ldecimalformat_Format.format(ai_Number);
		} catch (Exception e) {
		  	printMsg("formatNumber(): " + e.getMessage());
		  	ls_Formatted = Integer.toString(ai_Number);
		}

		return ls_Formatted;
	}
	
    /**
     * 格式化数字.
     * @param al_Number 数字
     * @param as_Pattern 指定的格式
     * @return 格式化之后的字符串
     */
    public static String format(long al_Number,String as_Pattern){
        return formatNumber(al_Number,as_Pattern);
    }
    
    /**
     * 格式化数字.
     * @param al_Number 数字
     * @param as_Pattern 指定的格式
     * @return 格式化之后的字符串
     */
	public static String formatNumber(long al_Number,String as_Pattern){
		DecimalFormat ldecimalformat_Format;
		String ls_Formatted;

		try {
			ldecimalformat_Format = new DecimalFormat(as_Pattern);
			ls_Formatted = ldecimalformat_Format.format(al_Number);
		} catch (Exception e){
		  	printMsg("formatNumber(): " + e.getMessage());
		  	ls_Formatted = Double.toString(al_Number);
		}

		return ls_Formatted;
	}

	public static double parseDouble(String as_Str){
		if (as_Str == null) return 0;
		
		double ldbl_Value;
		String ls_String = "";
		char[] larrs_String;
		int i;

		//get rid of the "," in the string
		larrs_String = as_Str.toCharArray();
		for (i = 0; i < larrs_String.length; i++) { 
            if (larrs_String[i] != ',') { 
                ls_String += larrs_String[i];
		    }
		}

		ldbl_Value = Double.parseDouble(ls_String);

		return ldbl_Value;
	}

	public static long parseLong(String as_Str, long al_Default){
		return (long)parseDouble(as_Str,(double)al_Default);
	}

	public static long parseLong(String as_Str){
		return (long)parseDouble(as_Str);
	}

	public static int parseInt(String as_Str, int ai_Default){
		return (int)parseDouble(as_Str,(double)ai_Default);
	}

	public static int parseInt(String as_Str){
		return (int)parseDouble(as_Str);
	}

	public static double parseDouble(String as_Str, double adbl_Default){
		double ldbl_Value;
		String ls_String = "";
		char[] larrs_String;
		int i;

		if (as_Str == null) return adbl_Default;
		as_Str = as_Str.trim();

		//get rid of the "," in the string
		larrs_String = as_Str.toCharArray();
		for (i = 0; i < larrs_String.length; i++) {
            if (larrs_String[i] != ',') {
                ls_String += larrs_String[i];
		    }
		}

		if (isNumber(ls_String))
			ldbl_Value = Double.parseDouble(ls_String);
		else
			ldbl_Value = adbl_Default;

		return ldbl_Value;
	}

	public static String formatNumber(float af_Number,String as_Pattern){
		DecimalFormat ldecimalformat_Format;
		String ls_Formatted;

		try {
			ldecimalformat_Format = new DecimalFormat(as_Pattern);
			ls_Formatted = ldecimalformat_Format.format(af_Number);
    	} catch (Exception e) {
    	  	printMsg("formatNumber(): " + e.getMessage());
    	  	ls_Formatted = Double.toString(af_Number);
    	}

		return ls_Formatted;
	}

	public static String emptyToZeroS(String as_Number){
		if (as_Number == null || as_Number.trim().equals(""))
		   return "0";
		else
		   return as_Number;
	}

	public static String invalidNumberToZeroS(String as_Number){
		if (isNumber(as_Number))
		   return as_Number;
		else
		   return "0";
	}

    public static String zeroToEmptyS(String as_String) {
        return zeroToEmpty(as_String);
    }
    
    /**
     * 给定一个字符串，如果其值代表0（无论是否带小数点），那么都返回空白字符串"".
     * @param as_String
     * @return 字符串。如果为0或者null，那么返回"".
     */
    public static String zeroToEmpty(String as_String) {
        if (as_String == null) return "";

        if (isNumber(as_String)){
            double ldbl_Value = CommonUtil.parseDouble(as_String);
            if (ldbl_Value == 0) return "";
        }

        return as_String;
    }
    
    /**
     * 给定一个数字，如果其值代表0（无论是否带小数点），那么都返回空白字符串"".
     * @param as_String
     * @return 字符串。如果为0或者null，那么返回"".
     */
    public static String zeroToEmpty(double adbl_Number) {
        if (adbl_Number == 0) return "";
        
        return Double.toString(adbl_Number);
    }
    
    /**
     * 给定一个数字，如果其值代表0（无论是否带小数点），那么都返回空白字符串"".
     * @param al_Number
     * @return 字符串。如果为0或者null，那么返回"".
     */
    public static String zeroToEmpty(long al_Number) {
        if (al_Number == 0) return "";
        
        return Long.toString(al_Number);
    }

	public static String nullToZeroS(String as_Number){
		return nullToZero(as_Number);
	}
    
    /**
     * 给定一个数字字符串，如果为null那么返回0.
     * @param as_Number 字符串.
     * @return
     */
    public static String nullToZero(String as_Number){
        if (as_Number == null) return "0";
        if ((as_Number.trim()).equals("")) return "0";

        return as_Number;
    }

	public static String nullToEmptyS(String as_String){		
		return nullToEmpty(as_String);
	}
    
    /**
     * 如果为null，那么返回""，否则原封不动地返回.
     * @param as_String
     * @return
     */
    public static String nullToEmpty(String as_String){
        if (as_String == null) return "";
        return as_String;
    }

    /**
     * @deprecated
     * @see #trim(String)
     * @param as_String
     * @return
     */
	public static String nullToEmptySTrim(String as_String){
		return nullToEmpty(as_String).trim();
	}
	
	/**
     * 判断某个对象实例是否“空”的。
     * 如果是字符串，那么如果长度为0或者都是空格也返回true.
     * 如果是Collection，那么如果为null或者size()为0都返回true.
     * @param obj 对象实例
     * @return true或者false
     */
    @SuppressWarnings("rawtypes")
	public static boolean isNullOrEmpty(final Object obj){
        if (obj == null) return true;
        
        if (obj instanceof String) {
        	return CommonUtil.trim(((String)obj)).length() == 0;
        } else  if (obj instanceof Collection) {
        	return ((Collection)obj).size() == 0;
        }
        
        return false;
    }
	
    /**
     * 判断某个对象实例是否“空”的。如果是字符串，那么如果长度为0或者都是空格也返回true.
     * @param aobj_O 对象实例
     * @return true或者false
     */
    public static boolean isEmpty(Object aobj_O){
        if (aobj_O == null) return true;
        
        if (aobj_O instanceof String) {
        	return CommonUtil.trim(((String)aobj_O)).length() == 0;
        }
        
        return false;
    }
    
    public static String trim(String as_String){
        if (as_String == null) return "";
        return as_String.trim();
    }
    
    /**
     * 去掉字符串左边的空格.
     * @param as_String
     * @return
     */
    public static String lTrim(String as_String) {
        if (as_String == null) return "";
        return as_String.replaceAll("^\\s+", ""); 
    }
    
    /**
     * 去掉字符串右边的空格.
     * @param as_String
     * @return
     */
    public static String rTrim(String as_String) {
        if (as_String == null) return "";
        return as_String.replaceAll("\\s+$", ""); 
    }

    public static String toUTF8String(String as_In){
        final int MAX_CHAR = 255;
        StringBuffer lsb_Buffer = new StringBuffer();
        
        for (int i = 0; i < as_In.length(); i++) {
            char c = as_In.charAt(i);
            if (c >= 0 && c <= MAX_CHAR) {
                    lsb_Buffer.append(c);
            } else {
                    byte[] b;
                    Character lchar_Char = new Character(c);
                    try {
                            b = lchar_Char.toString().getBytes("UTF-8");
                    } catch (Exception ex) {
                            System.out.println(ex);
                            b = new byte[0];
                    }

                    for (int j = 0; j < b.length; j++){
                            int k = b[j];
                            if (k < 0) k += (MAX_CHAR + 1);
                            lsb_Buffer.append("%" + Integer.toHexString(k).toUpperCase());
                    }
            }
        }
        return lsb_Buffer.toString();
    }


	public static boolean isDate(String as_Str) { 
		SimpleDateFormat lsdf_Format = new SimpleDateFormat("yyyy-MM-dd");

		if (as_Str == null) return false;

		try { 
            lsdf_Format.setLenient(false); //to be precise
            lsdf_Format.parse(as_Str);
		} catch (ParseException e) {
		   return false;
		}

		return true;
	}

	public static boolean isDateTime(String as_Str) { 
		SimpleDateFormat lsdf_Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		if (as_Str == null) return false;

		try {
            lsdf_Format.setLenient(false); //to be precise
            lsdf_Format.parse(as_Str);
		} catch (ParseException e) {
		   return false;
		}

		return true;
	}

    /**
     * 将给定的字符串转换为Date.
     * @param as_Str
     * @return
     */
	public static java.util.Date parseDate(String as_Str){
        if (as_Str == null) return null;
        
        java.util.Date ld_Value = parseDateTime(as_Str);
        if (ld_Value != null) return ld_Value;
         
		SimpleDateFormat lsdf_Format = new SimpleDateFormat("yyyy-MM-dd");
 
		try { 
            lsdf_Format.setLenient(false); //to be precise
            ld_Value = lsdf_Format.parse(as_Str);
		} catch (ParseException e) {
		   return null;
		}

		return ld_Value;
	}
    
    public static java.util.Date parseTime(String as_Str){
        java.util.Date ld_Value;
        SimpleDateFormat lsdf_Format = new SimpleDateFormat("HH:mm:ss");

        if (as_Str == null) return null;

        try { 
            lsdf_Format.setLenient(false); //to be precise
            ld_Value = lsdf_Format.parse(as_Str);
        } catch (ParseException e) {
           return null;
        }

        return ld_Value;
    }

    /**
     * 将给定的字符串转换为"日期/时间"Date实例.
     * @param as_Str
     * @return
     */
	public static java.util.Date parseDateTime(String as_Str){
        if (as_Str == null) return null;
        
		Date ld_Value = parseDate(as_Str, "yyyy-MM-dd HH:mm:ss");
        if (ld_Value != null) return ld_Value;
        
        ld_Value = parseDate(as_Str, "yyyy-MM-dd HH:mm");
        if (ld_Value != null) return ld_Value;
         
        ld_Value = parseDate(as_Str, "yyyy-MM-dd HH");
        if (ld_Value != null) return ld_Value;
        
		return null;
	}
    
    /**
     * 按照指定的方式将字符串转换为Date实例.
     * @param as_Str
     * @param as_Pattern
     * @return
     */
    private static Date parseDate(String as_Str, String as_Pattern) {
        if (as_Str == null) return null;
        
        java.util.Date ld_Value;
        SimpleDateFormat lsdf_Format = new SimpleDateFormat(as_Pattern);

        try { 
            lsdf_Format.setLenient(false); //to be precise
            ld_Value = lsdf_Format.parse(as_Str);
        } catch (ParseException e) {
           return null;
        }

        return ld_Value;
    }

    /**
     * 格式化字符串.
     * @param as_Value 字符串
     * @param as_Pattern 格式
     * @return 格式化后的字符串
     */
    public static String format(String as_Value, String as_Pattern){
        if (CommonUtil.isDate(as_Value) || CommonUtil.isDateTime(as_Value)) { 
            return formatDate(as_Value, as_Pattern);
        } else if(CommonUtil.isNumber(as_Value)) {
            return format(CommonUtil.parseDouble(as_Value), as_Pattern);
        }
        
        return as_Value;
    }
    
    /**
     * 格式化日期.
     * @param as_Date 日期字符串
     * @param as_Pattern 格式
     * @return 格式化后的日期
     */
	public static String formatDate(String as_Date, String as_Pattern){
		java.util.Date ld_Date;

		if (as_Pattern == null) {
		  	printMsg("formatDate(): as_Pattern is null");
		  	return null;
		}

		ld_Date = parseDateTime(as_Date);
		//可能只是Date型，进行parseDate
		if (ld_Date == null) {
			ld_Date = parseDate(as_Date);
		}

		if (ld_Date == null) return null; 

		return formatDate(ld_Date,as_Pattern);
	}
	
    /**
     * 格式化日期.
     * @param as_Date 日期字符串
     * @param as_Pattern 格式
     * @return 格式化后的日期
     */
	public static String formatDate(long as_Date, String as_Pattern){

		if (as_Pattern == null) {
		  	printMsg("formatDate(): as_Pattern is null");
		  	return null;
		}

		return format(new java.util.Date(as_Date), as_Pattern);
	}

    /**
     * 格式化日期.
     * @param ad_Date 日期
     * @param as_Pattern 格式
     * @return 格式化之后的日期
     */
    public static String format(java.util.Date ad_Date,String as_Pattern){
        return formatDate(ad_Date, as_Pattern);
    }
    
    /**
     * 格式化日期.
     * @param ad_Date 日期
     * @param as_Pattern 格式
     * @return 格式化之后的日期
     */
	public static String formatDate(java.util.Date ad_Date,String as_Pattern){
		SimpleDateFormat lsdf_Format;
		String ls_Formatted;

		if (as_Pattern == null) { 	
            printMsg("formatDate(): as_Pattern is null");
		  	return null;
		}
		if (ad_Date == null) { 	
            //printMsg("formatDate(): ad_Date is null");
		  	return null;
		}

		try {	lsdf_Format = new SimpleDateFormat(as_Pattern);
			ls_Formatted = lsdf_Format.format(ad_Date);
		} catch (Exception e) {
		  	printMsg("formatDate(): " + e.getMessage());
		  	lsdf_Format = new SimpleDateFormat("yyyy-MM-dd");
		  	ls_Formatted = lsdf_Format.format(ad_Date);
		}

		return ls_Formatted;
	}

	public static boolean isTimestamp(String as_Str){
		Timestamp lts_Value;  

		if (as_Str == null) return false;
		as_Str = as_Str.trim();

		try { 
            lts_Value = Timestamp.valueOf(as_Str);
		   //System.out.println(lts_Value);
		   //conver the lts_Value back to a string
		   lts_Value.toString();
		} catch (Exception e) { System.out.println("isTimestamp():" + e.getMessage());
		   return false;
		}
 
		return true;
	}

	public static String updateQueryString(String as_QueryString, String as_QueryParam,
			 String as_QueryParamValue){
		StringTokenizer lstringtokenizer_QueryString,lstringtokenizer_QueryStringUpperCase;
		String ls_Temp,ls_TempUpperCase,ls_QueryStringUpperCase,ls_QueryParamUpperCase;
		boolean lbool_Found = false;
		String ls_Return;

		//if the parameter name is null or "", just return
		if (as_QueryParam == null) as_QueryParam = "";
		as_QueryParam = as_QueryParam.trim();
		if (as_QueryParam == "") return as_QueryParam;

		if (as_QueryString == null) as_QueryString = "";
		if (as_QueryParamValue == null) as_QueryParamValue = "";
		as_QueryParamValue = as_QueryParamValue.trim();

		//get the upper case of the two strings
		ls_QueryStringUpperCase = as_QueryString.toUpperCase();
		ls_QueryParamUpperCase = as_QueryParam.toUpperCase();

		ls_Return = "";
		lstringtokenizer_QueryString = new StringTokenizer(as_QueryString,"&");
		lstringtokenizer_QueryStringUpperCase  = new StringTokenizer(ls_QueryStringUpperCase,"&");
		//find out if the as_QueryParam exists in the as_QueryString;
		while (lstringtokenizer_QueryStringUpperCase.hasMoreTokens()) {  
            ls_Temp = lstringtokenizer_QueryString.nextToken();
            ls_TempUpperCase = lstringtokenizer_QueryStringUpperCase.nextToken();
            if (ls_TempUpperCase.indexOf(ls_QueryParamUpperCase,0) >= 0) { 
                //found the as_QueryParam
               	ls_Temp = as_QueryParam + "=" + as_QueryParamValue;
               	lbool_Found = true;
            }
            if (!ls_Return.equals("")) ls_Return += "&";
            ls_Return += ls_Temp;
        }
		if (!lbool_Found) {	
            if (!ls_Return.equals("")) ls_Return += "&";
            ls_Return += as_QueryParam + "=" + as_QueryParamValue;
	    }
        
		return ls_Return;
	}

	public static String getEncodedString(String as_String){
		return getEncodedStringContent(as_String);
	}
	public static String getEncodedStringContent(String as_String){
		String ls_Return;
		char lc_Letter;
		int i;

		if (as_String == null) return null;


		ls_Return = "";
		for (i = 0; i < as_String.length(); i++) { 
            lc_Letter = as_String.charAt(i);
		    if (lc_Letter == '\\' || lc_Letter == '"') {
                ls_Return += "\\";
            }
		    
            ls_Return += lc_Letter;
		}

		return ls_Return;
	}

    /**
     * 将给定的字符串截断成指定的长度. 如果是普通的ASCII码，那么算0.5个长度
     * @param as_String
     * @param ai_Length
     * @return
     */
	public static String stringTrimToLength(String as_String,int ai_Length){
		return trimToLength(as_String, ai_Length, true);
	}
    
    /**
     * 将给定的字符串截断成指定的长度. 如果是普通的ASCII码，那么算0.5个长度
     * @param as_String
     * @param ai_Length
     * @return
     */
    public static String trimToLength(String as_String,int ai_Length){
        return trimToLength(as_String, ai_Length, true);
    }
    
    /**
     * 将给定的字符串截断成指定的长度.
     * @param as_String 字符串.
     * @param ai_Length 指定的长度
     * @param abool_AsciiAsHalf 是否将ASCII字符（普通的大小写字母、数字和标点符号等）算0.5个字符
     * @return
     */
    public static String trimToLength(String as_String, int ai_Length, boolean abool_AsciiAsHalf) {
        final int SPACE_ASCII = 32;
        
        //若为空,则返回0长度字符串
        if (as_String == null) return "";
        //去掉头尾空格
        as_String = as_String.trim();
        
        //如果不考虑ASCII码的情况
        if (!abool_AsciiAsHalf) {
            if (as_String.length() > ai_Length) { 
                return as_String.substring(0, ai_Length) + "...";
            } else {
                return as_String;
            }
        }
        
        //考虑ASCII码的情况
        byte[] larrbyte_B = as_String.getBytes();
        int li_Lenght = ai_Length * 2;  //所需结果字符串的字节数,一个字符等于两个字节,因此乘2
        
        //若小于所需长度,则直接返回
        if(larrbyte_B.length <= li_Lenght) return as_String;
        
        //若大于所需长度,则截段
        int li_CurrLength = 0;  //当前结果字符串的长度
        int li_ChineseCount = 0;    //当前结果字符串中汉字的字节个数,一个汉字为两个字节
        byte[] larrbyte_Result = new byte[li_Lenght];   //结果串
        while (li_CurrLength < li_Lenght){
            byte lbyte_B = larrbyte_B[li_CurrLength];
            if (lbyte_B > 0){
                //说明不是汉字,则正常追加到字符串中
                larrbyte_Result[li_CurrLength] = lbyte_B;
            } else {
                //则说明是汉字.
                if(((li_Lenght - li_CurrLength) == 1 && li_ChineseCount % 2 == 0)){
                    larrbyte_Result[li_CurrLength] = SPACE_ASCII;//插入空格
                } else {
                    
                    larrbyte_Result[li_CurrLength] = lbyte_B;
                }
                li_ChineseCount++;
            }
            li_CurrLength++;
        }
         
        return new String(larrbyte_Result) + "...";
    }

	public static String getEncodedStringForHTML(String as_String){
		char[]  larrchar_Letters,larrchar_String;
		String[] larrs_LettersReplaced;
		String ls_Return = null; 
		//final int LETTERS_COUNT = 5; 

		if (as_String == null) return null;

		larrchar_Letters = new char[]{'&','"','<','>',' '};
		larrs_LettersReplaced = new String[]{"&amp;","&quot;","&lt;","&gt;","&nbsp;"};

        /*
		larrchar_Letters[0] = '&'; larrs_LettersReplaced[0] = "&amp;";
		larrchar_Letters[1] = '"'; larrs_LettersReplaced[1] = "&quot;";
		larrchar_Letters[2] = '<'; larrs_LettersReplaced[2] = "&lt;";
		larrchar_Letters[3] = '>'; larrs_LettersReplaced[3] = "&gt;";
		larrchar_Letters[4] = ' '; larrs_LettersReplaced[4] = "&nbsp;";
		*/
        
		ls_Return = as_String;
		for (int i = 0; i < larrchar_Letters.length; i++) {
			larrchar_String = ls_Return.toCharArray(); //get the characters
			ls_Return = "";	//clear ls_Return
			for (int j = 0; j < larrchar_String.length; j++) { 
                if (larrchar_String[j] == larrchar_Letters[i]) {
                    ls_Return += larrs_LettersReplaced[i];
                } else {
                    ls_Return += larrchar_String[j];
                }
			}
		}

		//get rid of "\r\n"
		while (ls_Return.indexOf("\r\n") > -1) { 	
            int li_Pos = ls_Return.indexOf("\r\n");
		  	ls_Return = ls_Return.substring(0,li_Pos) + "<br>" 
		  	        + ls_Return.substring(li_Pos + 2, ls_Return.length());
		}

		return ls_Return;
	}
  
    public static String encodeBASE64(String as_Str) {
        if (as_Str == null) return null;
        return encodeBASE64(as_Str.getBytes());
    }

    /**
     * @deprecated
     * @param as_Str
     * @return
     */
    public static String encodeBASE64ForURL(String as_Str) {
        if (as_Str == null) return null;
        return java.net.URLEncoder.encode(encodeBASE64(as_Str.getBytes()));
    }
 
    public static String encodeBASE64(byte[] aarrb_Bytes){
        //是否带有"\r"或"\n"
        if (aarrb_Bytes == null) return null;
        String ls_Encoded =  Base64.encodeBytes(aarrb_Bytes);
 
        String ls_Return = ls_Encoded;

        return ls_Return;
    }
 
    public static byte[] decodeBASE64(String as_Str){
        if (as_Str == null) return null;

        byte[] larrbyte_B = Base64.decode(as_Str);
        return larrbyte_B;
    }

    public static byte[] objectToBytes(java.io.Serializable aobj_O){
        if (aobj_O == null) {
            printMsg("objectToBytes(): " + aobj_O.getClass().getName() + " is null. ");
            return null;
        }
        
        try {
            ByteArrayOutputStream loutstr_OS = new ByteArrayOutputStream();

            ObjectOutputStream lobjos_OS = new ObjectOutputStream(loutstr_OS);
            //if the idbagent_Agent in lusrprf_U is not empty, error will occur, so set it to be null.
            lobjos_OS.writeObject(aobj_O);
            lobjos_OS.flush();
            lobjos_OS.close();

            //encode to the Base64
            byte[] larrbyte_OS = loutstr_OS.toByteArray();
            return larrbyte_OS;
        } catch (Exception e) {
            printMsg("objectToBytes(): " + aobj_O.getClass().getName() + " : " + e.getMessage());
            return null;
        }
    }

    public static Object bytesToObject(byte[] aarrbyte_Obj)  {
        Object lobj_Return = null;

        try {
            ByteArrayInputStream lbytearris_InputStream = new ByteArrayInputStream(aarrbyte_Obj);
            ObjectInputStream lobjis_Input = new ObjectInputStream(lbytearris_InputStream);
            lobj_Return = lobjis_Input.readObject();
        } catch (Exception e) {
            printMsg("bytesToObject():" + e.getMessage());
        }

        return lobj_Return;
    }


   /**
    * 访问指定的URL，并返回该URL的内容字符串.
    * @param url 指定的URL
    * @return 内容字符串
    */
    public static String accessURL(String url) {  
        return HttpUtil.accessURL(url, "");
    }
    
    /**
     * 访问指定的URL，并返回该URL的内容字符串.
     * @param url 指定的URL
     * @param charSet 处理返回的内容时所使用的字符集.
     * @return 内容字符串
     */
     public static String accessURL(String url, String charSet) {  
//         String ls_Return = "";
//         try {
//             java.net.URL lurl_URL = new java.net.URL(as_URL);
//             InputStream linstrm_In = lurl_URL.openStream();
//             
//             ls_Return = CommonUtil.getInputStreamAsString(linstrm_In);                 
//             linstrm_In.close();
//             
//         } catch (Exception e) {
//             printMsg("accessURL(): " + e.getMessage());
//         }
//  
//         return ls_Return;
         return HttpUtil.accessURL(url, charSet);
      }
    
    /**
     * 将输入流中的内容读入到byte数组中.
     * 注意：在读取完成之后，不会将流关闭（close），调用本方法后应关闭流
     * @param ais_In 输入流
     * @return byte[]。如果ais_In为null，那么返回null
     */
    @SuppressWarnings("unchecked")
    public static byte[] getInputStreamAsByteArray(InputStream ais_In){
        final int K = 1024;
        byte[] larrbyte_Return = null; 
        
        if (ais_In == null) {
            printMsg("getInputStreamAsByteArray(): ais_In is null");
            return null;
        }
        
        try { 
            int li_TotalLength = 0;
            Vector lvector_Content = new Vector(), lvector_ContentLength = new Vector();
            while (true) {
                byte[] larrbyte_Buffer = new byte[K];
                int li_BytesRead = ais_In.read(larrbyte_Buffer);
                if (li_BytesRead == -1) break;

                li_TotalLength += li_BytesRead;
                byte[] larrbyte_Read = new byte[li_BytesRead];
                for (int i = 0; i < li_BytesRead; i++) {
                    larrbyte_Read[i] = larrbyte_Buffer[i];
                }   

                lvector_Content.addElement(larrbyte_Read);
                lvector_ContentLength.addElement(Integer.toString(li_BytesRead));
            }
            //ais_In.close();

            //get the byte[]
            larrbyte_Return = new byte[li_TotalLength];
            int li_Index = 0;
            for (int i = 0; i < lvector_ContentLength.size(); i++) {
                byte[] larrbyte_IthRead = (byte[])lvector_Content.elementAt(i);
                String ls_BytesRead = (String)lvector_ContentLength.elementAt(i);
                int li_ByteRead = CommonUtil.parseInt(ls_BytesRead,0);
                for (int j = 0; j < li_ByteRead; j++) {
                    larrbyte_Return[li_Index] = larrbyte_IthRead[j];
                    li_Index++;
                }
            } 
        } catch (Exception e) {
           printMsg("getInputStreamAsByteArray():" + e.getMessage());
        } 
        
        return larrbyte_Return;
    }
        
    /**
     * 将输入流中的内容读入到字符串中.
     * 注意：在读取完成之后，不会将流关闭（close），调用本方法后应关闭流
     * @param inputStream 输入流
     * @return 字符串。如果ais_In为null，那么返回null
     */
    public static String getInputStreamAsString(InputStream inputStream){
        if (inputStream == null) {
            printMsg("getInputStreamAsString(): inputStream is null");
            return null;
        }
        
        byte[] larrbyte_Return = getInputStreamAsByteArray(inputStream);
        if (larrbyte_Return == null) return null;  
        
        return new String(larrbyte_Return);        
    }
    
    /**
     * 将输入流中的内容读入到字符串中.
     * 注意：在读取完成之后，不会将流关闭（close），调用本方法后应关闭流
     * @param inputStream 输入流
     * @return 字符串。如果ais_In为null，那么返回null
     */
    public static String getInputStreamAsString(InputStream inputStream, String charSet){
        if (inputStream == null) {
            printMsg("getInputStreamAsString(): inputStream is null");
            return null;
        }
        
        byte[] larrbyte_Return = getInputStreamAsByteArray(inputStream);
        if (larrbyte_Return == null) return null;  
        
        try {
            return new String(larrbyte_Return, charSet);
        } catch (UnsupportedEncodingException e) { 
            e.printStackTrace();
            return new String(larrbyte_Return);
        }        
    }
    
    public static String postToURL(String as_URL, String as_Content)
            throws IOException {
        String ls_Return = "";

        as_URL = CommonUtil.trim(as_URL);
        as_Content = CommonUtil.trim(as_Content);

        if (as_URL.length() == 0) {
            printMsg("postToURL(): empty URL");
            return "";
        }

        URL lurl_URL = new URL(as_URL);

        // URL connection channel.
        URLConnection lurlconn_URLConn = lurl_URL.openConnection();

        // Let the run-time system (RTS) know that we want input.
        lurlconn_URLConn.setDoInput(true);

        // Let the RTS know that we want to do output.
        lurlconn_URLConn.setDoOutput(true);

        // No caching, we want the real thing.
        lurlconn_URLConn.setUseCaches(false);

        // Specify the content type.
        lurlconn_URLConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        // Send POST output.
        DataOutputStream ldtos_OutputStream = new DataOutputStream(lurlconn_URLConn.getOutputStream());
        ldtos_OutputStream.writeBytes(as_Content);
        ldtos_OutputStream.flush();
        ldtos_OutputStream.close();

        // Get response data.
        DataInputStream ldtis_InputStream = new DataInputStream(lurlconn_URLConn.getInputStream());
        ls_Return = getInputStreamAsString(ldtis_InputStream);
        ldtis_InputStream.close();
        
        return ls_Return;
         
    }

//   public static org.jdom.Document getXML(String as_XML){
//        as_XML = CommonUtil.trim(as_XML); 
//        org.jdom.Document ldoc_Return = null;
//        try {
//            org.jdom.input.SAXBuilder lsaxbuilder_SAXB = new org.jdom.input.SAXBuilder();
//            ByteArrayInputStream lbytearris_InputStream = new ByteArrayInputStream(as_XML.getBytes());
//            ldoc_Return = lsaxbuilder_SAXB.build(lbytearris_InputStream);
//        } catch (Exception e) {
//            e.printStackTrace();
//            //printMsg("getXML(): " + e.getMessage());
//        }
//
//        return ldoc_Return;
//    }
//
//   public static String getXMLString(org.jdom.Document adoc_XML){
//        return getXMLString(adoc_XML,"GBK");
//   }
//
//   public static String getXMLString(org.jdom.Document adoc_XML, String as_CharSet) {
//        String ls_Return = "";
//        
//        if (adoc_XML == null) {
//            printMsg("getXMLString(): adoc_XML is null");
//            return null;
//        }
//
//        /*
//        //JDom1.0的写法
//        org.jdom.output.Format lfmt_F = org.jdom.output.Format.getRawFormat().setEncoding("GBK");
//        org.jdom.output.XMLOutputter lxmlop_Outputter = new org.jdom.output.XMLOutputter(lfmt_F);
//        */
//
//        //老版本JDom的写法
//        org.jdom.output.XMLOutputter lxmlop_Outputter = new org.jdom.output.XMLOutputter(" ",true);
//        if (CommonUtil.trim(as_CharSet).length() > 0)
//            lxmlop_Outputter.setEncoding(CommonUtil.trim(as_CharSet));
//
//        //get the string
//        try {
//            ByteArrayOutputStream loutputstream_XML = new ByteArrayOutputStream();
//            lxmlop_Outputter.output(adoc_XML, loutputstream_XML);
//            if (loutputstream_XML != null)
//                ls_Return = loutputstream_XML.toString();
//            else
//                printMsg("getXMLString(): louputstream_XML is null");
//        }  catch (java.io.IOException e) {
//            e.printStackTrace();
//            //printMsg("getXMLString(): " + e.getMessage());
//        }
//
//        return ls_Return;
//    }
//        
//    private static final String ELEMENT_ARRAY = "array";
//    private static final String ELEMENT_ARRAY_ELEMENT = "array_element";    
//    private static final String ELEMENT_ARRAY_ELEMENT_TYPE = "element_type";
//    private static final String ELEMENT_ARRAY_ELEMENT_CLASS = "element_class";
//    
//    /**
//     * 将List中的元素转化为XML字符串.
//     * alist_L中的元素将按照如下方式和优先级进行转换处理:<br>
//     * 1、如果是字符串，那么直接作为XML的一个element加入；<br>
//     * 2、如果实现了XMLizable接口，那么转化为XML字符串再作为XML文档的一个element加入；<br>
//     * 3、如果实现了Serializable接口，那么将其通过@see #objectToBytes(java.io.Serializable)方法将其转换为bytes[]并进行Base64编码后加入XML文档<br>
//     * 
//     * @param alist_L 需要转换为XML字符串的List实例
//     * @return
//     */
//    @SuppressWarnings("unchecked")
//    public static String getXMLFromList(List alist_L){
//        if(alist_L == null)  {
//            System.out.println(CommonUtil.class.getName() + ".getXMLFromList(): alist_L is null");
//            return null;
//        }
//        
//        Document ldoc_Array = null;
//        Element lelement_Root = new Element(ELEMENT_ARRAY);
//        ldoc_Array = new Document(lelement_Root);
//        
//        for (int i = 0; i < alist_L.size(); i++) {
//            Object lobj_O = alist_L.get(i); 
//            if (lobj_O == null) continue;
//            
//            String ls_XML = null;
//            String ls_ElementType = "";
//            if (lobj_O instanceof String)   {
//                ls_XML = (String)lobj_O;
//                ls_ElementType = "String";
//            } else if (lobj_O instanceof XMLizable)  {
//                ls_XML = ((XMLizable)lobj_O).toXMLString();
//                ls_ElementType = "XMLizable";
//            }  else if (lobj_O instanceof Serializable) {
//                byte[] larrbyte_O = objectToBytes((Serializable)lobj_O);
//                ls_XML = encodeBASE64(larrbyte_O);
//                ls_ElementType = "Serializable";
//            } else {
//                System.out.println(CommonUtil.class.getName() + ".getXMLFromList(): " 
//                        + " perhaps the element(" + i + ") should not be transfer to String:"
//                        + lobj_O.getClass().getName());
//                continue;
//            }
//            
//            Element lelement_Element = new Element(ELEMENT_ARRAY_ELEMENT); 
//            lelement_Element.setText(ls_XML);
//            lelement_Element.setAttribute(ELEMENT_ARRAY_ELEMENT_TYPE,ls_ElementType);
//            lelement_Element.setAttribute(ELEMENT_ARRAY_ELEMENT_CLASS,lobj_O.getClass().getName());
//            lelement_Root.addContent(lelement_Element); 
//        } 
//
//        return getXMLString(ldoc_Array); 
//    }
//    
//    /**
//     * 从一个XML字符串中还原出List实例.
//     * @see #getXMLFromList(List)
//     * @param as_XML XML字符串
//     * @return List实例。如果XML字符串非法等情况出现那么返回null
//     */
//    @SuppressWarnings("unchecked")
//    public static List getListFromXML(String as_XML){
//        String ls_XML = CommonUtil.trim(as_XML);
//        if (ls_XML.length() == 0) {
//            System.out.println(CommonUtil.class.getName() + ".getListFromXML(): as_XML is empty");
//            return null;
//        }
//        
//        List llist_Return = new Vector(); 
//        try {
//            Document ldoc_XML = CommonUtil.getXML(ls_XML);  
//            Element lelement_Root = ldoc_XML.getRootElement();
//
//            java.util.List llist_Elements = lelement_Root.getChildren(); 
//           
//            for (int i = 0; i < llist_Elements.size(); i++) {
//                Element lelement_E = (Element)llist_Elements.get(i);
//                String ls_ElementStr = lelement_E.getText();
//                String ls_ElementType = lelement_E.getAttributeValue(ELEMENT_ARRAY_ELEMENT_TYPE);
//                String ls_ClassName = lelement_E.getAttributeValue(ELEMENT_ARRAY_ELEMENT_CLASS);
//                
//                if (ls_ElementType.equals("String"))
//                    llist_Return.add(ls_ElementStr);
//                else if (ls_ElementType.equals("XMLizable")) {
//                    try  {
//                        Class lclass_C = Class.forName(ls_ClassName); 
//                        Object lobj_O = lclass_C.newInstance(); 
//                        XMLizable lxmlizable_X = (XMLizable) lobj_O;  
//                        lxmlizable_X.initFromXMLString(ls_ElementStr); 
//                        llist_Return.add(lxmlizable_X);
//                    } catch (Exception e)  {
//                        System.out.println(CommonUtil.class.getName() + ".getListFromXML():在获取类时出现错误：" + ls_ClassName);
//                        System.out.println("请确认指定的类名(包括包名)是否正确，且实现了" + XMLizable.class.getName() + "接口。"); 
//                        System.out.println(e.getMessage());
//                    }
//                } else if (ls_ElementType.equals("Serializable")) {
//                    byte[] larrbyte_O = decodeBASE64(ls_ElementStr);
//                    Object lobj_O = bytesToObject(larrbyte_O);
//                    llist_Return.add(lobj_O);
//                }               
//            }
//        } catch (Exception aexception_E) {
//            System.out.println(CommonUtil.class.getName() + ".getListFromXML(): " + aexception_E.getMessage());
//            return null;
//        }
//        
//        return llist_Return;
//    }    
    
    /**
     * 比较两个数字. 如果A大于B，那么返回大于0的数；如果A等于B，那么返回0；如果A小于B，那么返回小于0的数字。
     * 本方法将double类型的数字格式化为"#####.#####"后再进行比较，如果出现了小数位超过5位的情况，返回值可能会不正确。
     * @param numberA 数字A
     * @param numberB 数字B
     * @return
     */
    public static int compareNumbers(double numberA, double numberB) {
        final String FORMAT = "######.#####";
        double valueA = CommonUtil.parseDouble(CommonUtil.format(numberA, FORMAT));
        double valueB = CommonUtil.parseDouble(CommonUtil.format(numberB, FORMAT));
        
        if (valueA > valueB) {
            return 1;
        } else if (valueA == valueB) {
            return 0;
        } else {
            return -1;
        }
    }
    
    /**
     * 比较两个数字. 如果A大于B，那么返回大于0的数；如果A等于B，那么返回0；如果A小于B，那么返回小于0的数字。
     * 本方法将double类型的数字格式化为"#####.#####"后再进行比较，如果出现了小数位超过5位的情况，返回值可能会不正确。
     * @param numberA 数字A
     * @param numberB 数字B
     * @return
     */
    public static boolean equals(double numberA, double numberB) {
        return compareNumbers(numberA, numberB) == 0;
    }
    
    /**
     * 将指定的文件读入到byte数组中.
     * @param file
     * @return
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
	public static byte[] readFile(File file) { 
    	if (file == null) {
    		printMsg("readFile(): file is null.");
    		return null;
    	}
    	
        InputStream in = null; 
        
        List < Byte > byteList = new ArrayList();
        try {
            byte[] tempbytes = new byte[1];
            in = new FileInputStream(file); 
            // 读入多个字节到字节数组中，byteread为一次读入的字节数
            while (in.read(tempbytes) != -1) {
            	byteList.add(tempbytes[0]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                	e.printStackTrace();
                }
            }
        }
        
        byte[] bytes = new byte[byteList.size()];
        for (int i = 0; i < byteList.size(); i++) {
        	bytes[i] = byteList.get(i).byteValue();
        }
        return bytes;
    }
    
    /**
     * 通过System.out.println()的方式在控制台显示相应提示信息.
     * @param as_Msg 提示信息内容
     */
    private static void printMsg(String as_Msg) {
        System.out.println(CommonUtil.class.getName() + ":" + as_Msg);
    }
    
//    /**
//     * 通过System.out.println()的方式在控制台显示相应提示信息.
//     * @param as_MethodName 提示信息所在的方法名
//     * @param as_Msg 提示信息内容
//     */
//    private static void printMsg(String as_MethodName, String as_Msg) {
//        System.out.println(CommonUtil.class.getName() + "." + as_MethodName + " : " + as_Msg);
//    }
    
    public static String getClassKey(String path, String key) {
    	Properties pro = getProperties(path);
    	
    	if (pro == null) {
    		
			return null;
		}
    	
        return pro.getProperty(key);
    }
    
    public static String getPropertyByKey(String path, String key) {
    	Properties pro = getProperties(path);
    	
    	if (pro == null) {
    		
			return null;
		}
    	
        return pro.getProperty(key);
    }
   
    /**
     * 读取配置属性.
     * @return
     */
    public static Properties getProperties(String path) {
        
        return loadProperties(path);
    }

    /**
     * 从properties文件读取文件.
     * @param path 
     */
    public static Properties loadProperties(String path) {
        InputStream in = null;
        Properties properties = null;
        
        try {
			/**
			 * Class.getResourceAsStream(String path) ： 
			 * path 以’/'开头,从class根目录下取
			 * 其只是通过path构造一个绝对路径，最终还是由ClassLoader获取资源。
			 */
            in = CommonUtil.class.getResourceAsStream(path); 
            properties = new Properties(); 
            properties.load(in);
            
        } catch (FileNotFoundException fnfe) { 
            fnfe.printStackTrace();
        } catch (IOException e) { 
            e.printStackTrace();
        } finally {
            try {
                if (in != null) in.close();
            } catch (IOException e) { 
                e.printStackTrace();
            }
        }
        
        return properties;
    } 
    
    public static final char UNDERLINE='_';
    
    public static String camelToUnderline(String param){  
        if (param==null||"".equals(param.trim())){  
            return "";  
        }  
        int len=param.length();  
        StringBuilder sb=new StringBuilder(len);  
        for (int i = 0; i < len; i++) {  
            char c=param.charAt(i);  
            if (Character.isUpperCase(c)){  
                sb.append(UNDERLINE);  
                sb.append(Character.toLowerCase(c));  
            }else{  
                sb.append(c);  
            }  
        }  
        return sb.toString();  
    }
    
	//base64字符串转化成图片  
    public static boolean generateImage(String imgStr, String folderName, String imgName)  
    {   //对字节数组字符串进行Base64解码并生成图片  
        if (imgStr == null) //图像数据为空  
            return false;   
        try   
        {  
        	//先判断图片字符串中是否含有base64开头的前缀，有的话就给去掉。
        	if (imgStr.indexOf("base64,") != -1) {
            	imgStr = imgStr.substring(imgStr.indexOf("base64,") + 7, imgStr.length() - 1);
			}
    	
            //Base64解码  
            byte[] b = Base64.decodeBase64(imgStr);  
            for(int i=0;i<b.length;++i)  
            {  
                if(b[i]<0)  
                {//调整异常数据  
                    b[i]+=256;  
                }  
            }  
            //生成jpeg图片  
            String imgFilePath = folderName + File.separator + imgName;//新生成的图片  
            File folderPath = new File(folderName);
            if(!folderPath.exists())
            	folderPath.mkdir();
            OutputStream out = new FileOutputStream(imgFilePath);      
            out.write(b);  
            out.flush();  
            out.close();  
            return true;  
        }   
        catch (Exception e)   
        {  
            return false;  
        }  
    } 
    
    
    public static void main(String[] args) {
		System.out.println(getClassKey("/EIPService.properties", "isToken"));
	}
}

